package uk.ac.lkl.lpp.model.xml;



import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import uk.ac.lkl.common.util.ds.AbstractNotifyingList;
import uk.ac.lkl.common.util.ds.NotifyingList;
import uk.ac.lkl.common.util.ds.NotifyingSubList;

import uk.ac.lkl.lpp.model.PedagogyPlanModel;

import uk.ac.lkl.lpp.model.ldo.TeachingMethod;
import uk.ac.lkl.lpp.ui.BackCompat;


public class SelectedTeachingMethodSetProcessor extends ModelElementProcessor {

    public SelectedTeachingMethodSetProcessor() {
        super("SelectedTeachingMethodSet");
    }


    /**
     * write TMs to TeachingMethodSet element
     */
    public void convertDataToElements(PedagogyPlanModel plan,
                                      Document document,
                                      Element pedagogyPlanElement) {
        // should be done in base class
        Element teachingMethodSetElement = document
                .createElement("SelectedTeachingMethodSet");
        pedagogyPlanElement.appendChild(teachingMethodSetElement);

        AbstractNotifyingList<TeachingMethod> list = plan
                .getList("selected", TeachingMethod.class);

        NotifyingSubList<TeachingMethod> subList = (NotifyingSubList<TeachingMethod>) list;

        for (TeachingMethod teachingMethod : subList) {
            Element teachingMethodElement = document
                    .createElement("TeachingMethod");
            int parentIndex = subList.getParentIndex(teachingMethod);
            teachingMethodElement.setAttribute("parentIndex", Integer
                    .toString(parentIndex));
            teachingMethodSetElement.appendChild(teachingMethodElement);
        }
    }


    public void convertElementToData(PedagogyPlanModel plan, Element element) {
        AbstractNotifyingList<TeachingMethod> mainList = plan
                .getList("main", TeachingMethod.class);
        NotifyingSubList<TeachingMethod> subList = new NotifyingSubList<TeachingMethod>(
                mainList);
        NodeList nodes = element.getElementsByTagName("TeachingMethod");
        for (int i = 0; i < nodes.getLength(); i++) {
            Element childElement = (Element) nodes.item(i);
            String parentIndexString = childElement.getAttribute("parentIndex");
            int parentIndex = Integer.parseInt(parentIndexString);
            subList.addElementByParentIndex(parentIndex);
        }
        plan.addList("selected", TeachingMethod.class, subList);
    }

}
